﻿using System;
using System.IO;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Navigation;
using Microsoft.Win32;
using WPF_DbCenter.CommonMethod;
using WPF_DbCenter.Utility;
using System.Collections.Generic;
using WPF_DbCenter.UI;
using WPF_DbCenter.BaseUI;
using CustomControl.NewXLAGControl;
using System.Data.SqlServerCe;
using System.ComponentModel;
using System.Xml;
using System.Text;
using XLCS.Webs;
using XLCS.Common;
using System.Reflection;
using XLCS.Xml;
using WPF_DbCenter.SqlCE.AdditionUI;

namespace WPF_DbCenter
{
    public partial class AppEntry : Page
    {
        internal static string SQLCE_FILE_FILTER = "Sql Ce db file (*.sdf)|*.sdf|All Files(*.*)|*.*";
        internal static string MDB_FILE_FILTER = "MDB file (*.mdb)|*.mdb|All Files(*.*)|*.*";
        internal static string EXCEL_FILE_FILTER = "Excel file (*.xls)|*.xls|All Files(*.*)|*.*";
        internal static string CVS_FILE_FILTER = "Csv file (*.csv)|*.xls|Text file (*.txt)|*.txt|All Files(*.*)|*.*";

        public AppEntry()
        {
            if (System.Windows.Forms.ApplicationUtility.IsAlreadyRunning())
            {
                System.Windows.Forms.ApplicationUtility.BringOtherInstanceToFront();

            }

            this.InitializeComponent();

            InitSelf();

            // 在此点之下插入创建对象所需的代码。
        }

        private void InitSelf()
        {
            this.AllowDrop = true;
            this.Drop += new DragEventHandler(AppEntry_Drop);
            GlobalInfo._curHistoryList = new List<string>();
            RefreshLastOpenedDbsStatus();

            this.txtDbPath.SpellCheck.IsEnabled = true;

            this.comboBox1.Items.Add(new OpenModeClass() { mode = OpenMode.ReadWrite, modeDisplayName = "Read Write" });
            this.comboBox1.Items.Add(new OpenModeClass() { mode = OpenMode.ReadOnly, modeDisplayName = "Read Only" });
            this.comboBox1.Items.Add(new OpenModeClass() { mode = OpenMode.SharedRead, modeDisplayName = "Shared Read" });
            this.comboBox1.Items.Add(new OpenModeClass() { mode = OpenMode.Exclusive, modeDisplayName = "Exclusive" });
            this.comboBox1.SelectedIndex = 0;
        }


        void AppEntry_Drop(object sender, DragEventArgs e)
        {
            e.Handled = true;
            if (e.Data.GetDataPresent(DataFormats.FileDrop, true))
            {
                string[] fileNames = e.Data.GetData(DataFormats.FileDrop, true) as string[];
                if (fileNames.Length == 1)
                {
                    // Check for a file (a directory will return false).
                    if (File.Exists(fileNames[0]))
                    {
                        // At this point we know there is a single file.
                        txtDbPath.Text = fileNames[0];
                    }
                }

            }

        }

        private void RefreshLastOpenedDbsStatus()
        {
            if (string.IsNullOrEmpty(Properties.Settings.Default.LastestOpenedDb))
            {
                butOpenLastest.Visibility = Visibility.Hidden;
            }
            else
            {
                butOpenLastest.Visibility = Visibility.Visible;
            }

            if (!File.Exists(Config.DbHistoryFileFullPath))
            {
                this.butHistory.Visibility = Visibility.Hidden;
            }
            else
            {
                this.butHistory.Visibility = Visibility.Visible;
                GlobalInfo._curHistoryList = SerializeClass.GetHistoryList();
            }

        }
        private void butSync_Click(object sender, RoutedEventArgs e)
        {
            UI.DataExchange exchange = new WPF_DbCenter.UI.DataExchange();
            exchange.ShowDialog();
        }

        private void chkIsHasPwd_Checked(object sender, RoutedEventArgs e)
        {
            if ((bool)chkIsHasPwd.IsChecked)
            {

                txtPwd.Password = string.Empty;
            }
        }

        private void butSelectDb_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog of = new OpenFileDialog();
            of.Filter = SQLCE_FILE_FILTER;
            if (of.ShowDialog() == true)
            {
                this.txtDbPath.Text = of.FileName;
            }
        }

        private void butCreateEmptyDB_Click(object sender, RoutedEventArgs e)
        {
            UI.CreateEmptyDb cb = new WPF_DbCenter.UI.CreateEmptyDb();
            cb.CreateDbAfterSuccesful = new WPF_DbCenter.UI.CreateEmptyDb.Del_CreateDbAfterSuccesful(RefreshAfterCreateSuccess);
            cb.ShowDialog();
        }

        private void RefreshAfterCreateSuccess(string dbFullPath, string pwd)
        {
            if (!string.IsNullOrEmpty(dbFullPath))
            {
                txtDbPath.Text = dbFullPath;

            }
            if (!string.IsNullOrEmpty(pwd))
            {
                txtPwd.Password = pwd;

            }

        }

        private void butOpen_Click(object sender, RoutedEventArgs e)
        {
            string dbName = txtDbPath.Text;
            string dbPwd = txtPwd.Password;

            if (string.IsNullOrEmpty(dbName))
            {
                MessageBox.Show("Please input database name");
                return;
            }

            if (Utility.DetectNetworkDriver.IsPathOnNetworkDrive(dbName))
            {
                MessageBox.Show("SQLCE do not support open from network");
                return;
            }
            OpenModeClass CurOpenMode = null;
            if (comboBox1.SelectedItem == null)
            {
                CurOpenMode = comboBox1.Items[0] as OpenModeClass;
            }
            else
            {
                CurOpenMode = comboBox1.SelectedItem as OpenModeClass;
            }

            //If open db ok ,and get tables info ok , then do 
            //otherwise do nothing
            if (App.MainEngineer.OpenDatabase(dbName, txtPwd.Password, CurOpenMode))
            {
                ((CEEnginer)App.MainEngineer).CurPwd=txtPwd.Password;
                
                //this.Hide();
                txtDbPath.Text = string.Empty;
                txtPwd.Password = string.Empty;
                Properties.Settings.Default.LastestOpenedDb = dbName;
                Properties.Settings.Default.LastestOpenedDbPwd = dbPwd;
                Properties.Settings.Default.Save();

                if (!GlobalInfo._curHistoryList.Contains(dbName))
                {
                    GlobalInfo._curHistoryList.Add(dbName);

                    SerializeClass.SaveHistory(GlobalInfo._curHistoryList);
                }


                RefreshLastOpenedDbsStatus();

                IWindowIDE mainIDE = null;

                switch (Properties.Settings.Default.StartMainIDEStep)
                {
                    case 0:
                        //mainIDE = new OLD_Main();
                        break;
                    case 1:
                        mainIDE = new UI.Main();
                        break;
                    default:
                        //mainIDE = new OLD_Main();
                        break;
                }

                mainIDE.MyHost.Tag = this;
                mainIDE.MyHost.WindowState = WindowState.Maximized;
                mainIDE.MyHost.BringIntoView();
                mainIDE.MyHost.Show();
            }
        }

        private void butOpenLastest_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(Properties.Settings.Default.LastestOpenedDb))
            {
                return;
            }

            txtDbPath.Text = Properties.Settings.Default.LastestOpenedDb;
            txtPwd.Password = Properties.Settings.Default.LastestOpenedDbPwd;
            butOpen_Click(null, null);
        }

        private void butOpenHistory_Click(object sender, RoutedEventArgs e)
        {
            DynaControls.DbOpenedHistory history = new WPF_DbCenter.DynaControls.DbOpenedHistory();
            history.AfterSelectedValue += new WPF_DbCenter.DynaControls.DbOpenedHistory.Del_AfterSelectedValue(AfterSelect);

            history.ShowDialog();
        }

        private void AfterSelect(string args)
        {
            if (!string.IsNullOrEmpty(args))
            {
                this.txtDbPath.Text = args;
            }

        }

        /// <summary>
        /// Change pwd 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            string db = this.txtDbPath.Text;
            if (string.IsNullOrEmpty(db))
            {
                MessageBox.Show("Please select database first");
                return;
            }
            ChangeSdfPwd ch = new ChangeSdfPwd(db);
            if ((bool)ch.ShowDialog() == true)
            {
                txtPwd.Password = ch.NewPwd;
            }

        }

        /// <summary>
        /// Live Update From UI
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void LiveUpdate(object sender, RoutedEventArgs e)
        {

            BackgroundWorker worker = new BackgroundWorker();
            worker.DoWork += new DoWorkEventHandler(worker_DoWork);
            worker.RunWorkerAsync();

        }

        void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            string tempFile = "C:\\TempLiveFile.xml";
            string tempUpdateExe = "C:\\TempUpdate.rar";

            try
            {
                StringBuilder detail = GetOnlineResources.GetOnlineHtmlFromURL(Properties.Settings.Default.LiveUpdateAddress);

                XmlDocument xml = new XmlDocument();
                xml.LoadXml(detail.ToString());
                xml.Save(tempFile);

                string result = string.Empty;

                OldSelfDefined.retriveObjForFirst(tempFile, "Version", out result);

                int nextVersion = Convert.ToInt32(result.Replace('.', '2'));
                int curVersion = Convert.ToInt32(Assembly.GetExecutingAssembly().GetName().Version.ToString().Replace('.', '2'));
                if (nextVersion > curVersion)
                {
                    if (System.Windows.Forms.MessageBox.Show(String.Format("New version {0} existed ,do you want to update ?", result), "Notify", System.Windows.Forms.MessageBoxButtons.OKCancel,
                        System.Windows.Forms.MessageBoxIcon.Question, System.Windows.Forms.MessageBoxDefaultButton.Button2) == System.Windows.Forms.DialogResult.OK)
                    {
                        string updateAddress = string.Empty;
                        OldSelfDefined.retriveObjForFirst(tempFile, "Address", out updateAddress);
                        if (string.IsNullOrEmpty(updateAddress))
                        {
                            MessageBox.Show("Invalid address ,update will cancel");
                            return;
                        }

                        updateAddress = Properties.Settings.Default.LiveUpdateAddress + "\\" + updateAddress;

                        using (WebClient Client = new WebClient())
                        {
                            Client.DownloadFile(updateAddress, tempUpdateExe);
                        }

                        MessageBox.Show("Get Update file successful ");
                    }
                }
                else
                {
                    MessageBox.Show("Your version is up-to-date");
                }
            }
            catch (Exception ee)
            {
                ProcessException.DisplayErrors(ee);

            }
            finally
            {
                if (File.Exists(tempFile))
                {
                    File.Delete(tempFile);
                }
                if (File.Exists(tempUpdateExe))
                {
                    File.Delete(tempUpdateExe);
                }
            }

        }

        private void button1_Click_1(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(txtDbPath.Text))
            {
                MessageBox.Show("Please select db file first");
                return;
            }
            string db = txtDbPath.Text;
            string result=XLCS.Sqlce.UndocumentedFunctions.GetCeVersion(db);
            MessageBox.Show(String.Format("Version : Sql Ce {0}", result));

        }
    }
}
